<template>
  <div class="comment-manage">
    <div class="page-header">
      <h2>评论管理</h2>
    </div>
    
    <div class="search-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索评论内容、用户名或文章标题"
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      <el-button @click="handleReset" type="info" plain>
        <el-icon><Refresh /></el-icon>
        重置
      </el-button>
    </div>
    
    <!-- 评论列表 -->
    <div class="comment-table">
      <el-table
        v-loading="loading"
        :data="commentList"
        style="width: 100%"
        border
      >
        <el-table-column prop="commentId" label="ID" width="80" />
        <el-table-column label="评论内容" min-width="200">
          <template #default="{ row }">
            <div class="comment-content">
              <el-tooltip :content="row.commentText" placement="top">
                <span class="comment-text">{{ row.commentText.length > 8 ? row.commentText.slice(0, 8) + '...' : row.commentText }}</span>
              </el-tooltip>
              <el-tag v-if="row.parentCommentId" size="small" type="info">回复</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" width="150">
          <template #default="{ row }">
            <el-tooltip :content="'用户ID: ' + row.userId" placement="top">
              <span>{{ row.userName }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="文章信息" min-width="200">
          <template #default="{ row }">
            <el-tooltip :content="'文章ID: ' + row.contentId + '\n' + row.articleTitle" placement="top">
              <el-button link type="primary" @click="handleArticleClick(row)">
                {{ row.articleTitle.length > 10 ? row.articleTitle.slice(0, 10) + '...' : row.articleTitle }}
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="likeCount" label="点赞数" width="100" />
        <el-table-column prop="createTime" label="评论时间" width="180">
          <template #default="{ row }">
            {{ $formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleReply(row)"
              :disabled="!!row.parentCommentId"
            >
              回复
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
            <el-button
              v-if="row.parentCommentId"
              type="info"
              size="small"
              @click="handleViewParent(row.parentCommentId)"
            >
              查看父评论
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 回复对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复评论"
      width="500px"
    >
      <el-form :model="replyForm" label-width="80px">
        <el-form-item label="回复内容">
          <el-input
            v-model="replyForm.commentText"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 父评论详情对话框 -->
    <el-dialog
      v-model="parentCommentDialogVisible"
      title="评论详情"
      width="700px"
    >
      <div class="parent-comment-detail">
        <!-- 父评论 -->
        <div class="parent-comment">
          <div class="comment-header">
            <div class="user-info">
              <el-avatar :size="40" :src="parentComment.userAvatar || defaultAvatar" />
              <div class="user-meta">
                <span class="username">{{ parentComment.userName }}</span>
                <span class="time">{{ $formatDate(parentComment.createTime) }}</span>
              </div>
            </div>
            <div class="comment-actions">
              <el-button type="primary" size="small" @click="handleReply(parentComment)">
                回复
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(parentComment)">
                删除
              </el-button>
            </div>
          </div>
          <div class="comment-content">
            <p class="comment-text">{{ parentComment.commentText }}</p>
            <div class="comment-meta">
              <span class="article-link" @click="handleArticleClick(parentComment)">
                文章：{{ parentComment.articleTitle }}
              </span>
              <span class="like-count">点赞：{{ parentComment.likeCount }}</span>
            </div>
          </div>
        </div>

        <!-- 回复列表 -->
        <div class="replies-section">
          <h3>回复列表 ({{ replies.length }})</h3>
          <div class="replies-list">
            <div v-for="reply in replies" :key="reply.commentId" class="reply-item">
              <div class="reply-header">
                <div class="user-info">
                  <el-avatar :size="32" :src="reply.userAvatar || defaultAvatar" />
                  <div class="user-meta">
                    <span class="username">{{ reply.userName }}</span>
                    <span class="time">{{ $formatDate(reply.createTime) }}</span>
                  </div>
                </div>
                <div class="reply-actions">
                  <el-button type="danger" size="small" @click="handleDelete(reply)">
                    删除
                  </el-button>
                </div>
              </div>
              <div class="reply-content">
                <p class="reply-text">{{ reply.commentText }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="parentCommentDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleBackToList">返回列表</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import axios from 'axios'

// 获取全局属性
const { proxy } = getCurrentInstance()

// 数据列表
const commentList = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const currentContentId = ref(null)

// 回复对话框
const replyDialogVisible = ref(false)
const replyForm = ref({
  commentId: null,
  commentText: '',
  contentId: null,
  userId: null,
  parentCommentId: null
})

// 父评论相关数据
const parentCommentDialogVisible = ref(false)
const parentComment = ref({})
const replies = ref([])
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 获取评论列表
const fetchComments = async () => {
  loading.value = true
  try {
    let url = '/api/comments/list'
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value
    }
    
    if (currentContentId.value) {
      url = `/api/comments/article/${currentContentId.value}`
    }
    
    const res = await axios.get(url, { params })
    if (res.data.code === 200) {
      commentList.value = res.data.data.list
      total.value = res.data.data.total
    } else {
      ElMessage.error(res.data.message || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索评论
const handleSearch = async () => {
  if (!searchKeyword.value) {
    fetchComments()
    return
  }
  loading.value = true
  try {
    const response = await axios.get('/api/comments/search', {
      params: { 
        keyword: searchKeyword.value,
        pageNo: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (response.data.code === 200) {
      commentList.value = response.data.data.list
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '搜索评论失败')
    }
  } catch (error) {
    console.error('搜索评论失败:', error)
    ElMessage.error('搜索评论失败')
  } finally {
    loading.value = false
  }
}

// 重置功能
const handleReset = () => {
  searchKeyword.value = ''
  currentContentId.value = null
  currentPage.value = 1
  pageSize.value = 10
  fetchComments()
  ElMessage.success('已重置搜索条件和分页')
}

// 处理回复
const handleReply = (row) => {
  replyForm.value = {
    commentId: null,
    commentText: '',
    contentId: row.contentId,
    userId: row.userId,
    parentCommentId: row.commentId
  }
  replyDialogVisible.value = true
}

// 提交回复
const submitReply = async () => {
  if (!replyForm.value.commentText) {
    ElMessage.warning('请输入回复内容')
    return
  }
  try {
    const response = await axios.post('/api/comments/add', replyForm.value)
    if (response.data.code === 200) {
      ElMessage.success('回复成功')
      replyDialogVisible.value = false
      fetchComments()
    } else {
      ElMessage.error(response.data.message || '回复失败')
    }
  } catch (error) {
    console.error('回复失败:', error)
    ElMessage.error('回复失败')
  }
}

// 点击文章标题
const handleArticleClick = (row) => {
  currentContentId.value = row.contentId
  currentPage.value = 1
  fetchComments()
  ElMessage.success(`正在查看文章ID: ${row.contentId} 的评论`)
}

// 查看父评论
const handleViewParent = async (parentCommentId) => {
  loading.value = true
  try {
    const response = await axios.get(`/api/comments/${parentCommentId}`)
    if (response.data.code === 200) {
      parentComment.value = response.data.data
      // 获取父评论的所有回复
      const repliesResponse = await axios.get(`/api/comments/replies/${parentCommentId}`)
      if (repliesResponse.data.code === 200) {
        replies.value = repliesResponse.data.data
        parentCommentDialogVisible.value = true
      }
    } else {
      ElMessage.error(response.data.message || '获取父评论失败')
    }
  } catch (error) {
    console.error('获取父评论失败:', error)
    ElMessage.error('获取父评论失败')
  } finally {
    loading.value = false
  }
}

// 返回列表
const handleBackToList = () => {
  parentCommentDialogVisible.value = false
  fetchComments()
}

// 删除评论
const handleDelete = (row) => {
  const isParentComment = !row.parentCommentId
  const confirmMessage = isParentComment 
    ? '确定要删除这条评论吗？删除后将同时删除所有回复，且无法恢复。'
    : '确定要删除这条评论吗？删除后将无法恢复。'

  ElMessageBox.confirm(
    confirmMessage,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await axios.delete(`/api/comments/delete/${row.commentId}`)
      if (response.data.code === 200) {
        ElMessage.success('删除成功')
        // 如果当前在评论详情对话框，则关闭对话框
        if (parentCommentDialogVisible.value) {
          parentCommentDialogVisible.value = false
        }
        // 刷新评论列表
        fetchComments()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchComments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchComments()
}

// 初始化
onMounted(() => {
  fetchComments()
})
</script>

<style scoped>
.comment-manage {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 400px;
}

.comment-table {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.comment-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.comment-text {
  word-break: break-all;
}

.reply-to {
  font-size: 12px;
  color: #666;
  background: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

.reply-dialog-content {
  padding: 20px;
}

.original-comment {
  margin-bottom: 20px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.original-comment h4 {
  margin: 0 0 8px 0;
  color: #666;
}

.original-comment p {
  margin: 0;
  color: #333;
}

.parent-comment-detail {
  padding: 20px;
}

.parent-comment {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-meta {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
}

.comment-actions {
  display: flex;
  gap: 8px;
}

.comment-content {
  margin-left: 52px;
}

.comment-text {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 12px;
}

.comment-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #666;
}

.article-link {
  color: #409EFF;
  cursor: pointer;
}

.article-link:hover {
  text-decoration: underline;
}

.replies-section {
  margin-top: 24px;
}

.replies-section h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.replies-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.reply-item {
  background: #fff;
  border-radius: 6px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.reply-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.reply-content {
  margin-left: 44px;
}

.reply-text {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.like-count {
  display: flex;
  align-items: center;
  gap: 4px;
}

.like-count::before {
  content: '👍';
  font-size: 14px;
}
</style>